In [28]:
from math import sqrt, pi

Trapezium Rule


In [45]:
Nstrips = 100000  #Number of elements
h = 1.0/Nstrips    #Stepsize
sum_of_ys = 0.0    #This will contain only the sum from y_1 to y_(n-1)
x = 0.0            #The x-coordinate on the graph y = 4*sqrt(1-x^2)

def y_equation(x :float):
    return(4.0*sqrt(1.0-x**2))

for i in range(Nstrips-1):
    x = (i+1)*h
    sum_of_ys += y_equation(x) #The sum from y_1 to y_(n-1) is calculated

#Apply the trapezium rule inteligently  h*(y_1+y_2+...+y_(n-1)) + 0.5*h*(y_0 + y_1)
area = h*(sum_of_ys + 0.5*(y_equation(0)+y_equation(1)))

print ('The area between curve and x-axis is: ', area)
print ('π =', pi, '\t ΔError =',pi-area )


The area between curve and x-axis is:  3.141592616402008
π = 3.141592653589793 	 ΔError = 3.7187785295600406e-08

Simpson's Rule


In [46]:
N = 100000
Nstrips = 2*N   #Number of elements
h = 1.0/Nstrips    #Stepsize
sum_of_oddstep_ys = 0.0    #This will contain only the sum of y_1, y_3, y_5 ...
sum_of_evenstep_ys = 0.0   #This will contain only the sum of y_2, y_4, y_6 ...

x = 0.0            #The x-coordinate on the graph y = 4*sqrt(1-x^2)

for i in range(N):
    x = (2*i+1.0)*h
    sum_of_oddstep_ys += y_equation(x) 
    x = (2*i+2.0)*h
    sum_of_evenstep_ys += y_equation(x)
    
#Apply Simpson's rule inteligently 
area = h*(sum_of_oddstep_ys*4.0/3.0 + sum_of_evenstep_ys*2.0/3.0 + y_equation(0)/3.0)

print ('The area between curve and x-axis is: ', area)
print ('π =', pi, '\t ΔError =',pi-area )


The area between curve and x-axis is:  3.1415926484552226
π = 3.141592653589793 	 ΔError = 5.13457054651667e-09

In [ ]: